package com.szxy.lockdemo;

/**
 * @Author: zwz
 * @Date:2020/10/23 17:58
 * @Description: 可重入锁， 同一个线程， 一个方法调用另一个方法
 **/
public class ComReentrantLockDemo {
    private boolean isLocked = false;
    private int lockCount = 0;
    private Thread lockBy;

    public synchronized void lock() throws InterruptedException {
        Thread cutThread = Thread.currentThread();
        while (isLocked && lockBy != cutThread) {
            wait();
        }
        isLocked = true;
        lockCount++;
        lockBy = cutThread;
    }

    public synchronized void unlock() {
        if (lockBy == Thread.currentThread()) {
            lockCount--;
            if (lockCount == 0) {
                isLocked = false;
                notify();
            }
        }
    }

}
